package com.loong.system.service.impl;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.loong.system.service.AliYunSmsService;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class AliYunSmsServiceImpl implements AliYunSmsService {
  @Value("${aliyun.sign-name}")
  private String signName; // 阿里云短信签名

  @Value("${aliyun.template-code}")
  private String templateCode; // 阿里云短信模板代码

  @Value("${aliyun.access-key-id}")
  private String accessKeyId; // 阿里云Access Key ID

  @Value("${aliyun.access-key-secret}")
  private String accessKeySecret; // 阿里云Access Key Secret

  @Override
  public void send(String mobile, String code) {
    DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
    IAcsClient client = new DefaultAcsClient(profile);
    SendSmsRequest request = new SendSmsRequest();
    request.setPhoneNumbers(mobile); // 设置手机号码
    request.setSignName(URLDecoder.decode(signName, StandardCharsets.UTF_8)); // 设置短信签名，进行URL解码
    request.setTemplateCode(templateCode); // 设置短信模板代码
    request.setTemplateParam("{\"code\":\"" + code + "\"}"); // 设置短信模板参数
    try {
      SendSmsResponse response = client.getAcsResponse(request);
      log.info("短信发送成功，返回状态码：{}", response.getCode()); // 输出返回状态码
    } catch (Exception e) {
      log.error(e.getMessage());
    }
  }
}
